#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <pthread.h>

#include "../notifyADT/notifyADT.h"
#include "../include/MQclient.h"
#include "../../common/include/commonMQ.h"
#include "../../common/include/filesystem.h"
#include "../../common/include/split.h"
#include "../../common/include/general.h"
#include "../include/client.h"
#include "../../common/include/common.h"

#define QUEUE_ID    200

/* watchList y MQ */
int mqid;
int cliID;
int pubcliID = 0;
int public;

/* Externs de client.c */
extern int logged;
extern watchD w;
extern char *syncPath;
extern char splitVal;
extern pthread_t threads[SPLITS_QUANTITY];
extern int sons[SPLITS_QUANTITY];
extern int doLS;
extern char lastComm[FILE_LEN];

char sess_name[MAX_NAME_LEN];

int
mainMQ (void)
{

    logged = 0;

    /* Handlers de SIGS */
    (void)signal(SIGINT, sighandINTMQ);

    /* ID de la  Cola de mensajes */
    mqid = msgget((key_t)QUEUE_ID, 0666 | IPC_CREAT);
    public = PUBLIC_MQSERV;

    cliID = getpid();

    readCommandsMQ();

    exit(0);
}

int nombreMQ(void)
{
    char name[MAX_NAME_LEN] = {0};
    char msg[100] = {0};
    int nwrite, ans, totlen, len =0;
    char resp[MSGSIZE+1] = {0};
    int move = 0, splitRet;

    fprintf (stdout, "\nInsert your name: ");
    getLine (name, MAX_NAME_LEN, stdin);

    len = strlen(name);
    strcpy(sess_name, name);

    sprintf(msg, "%d,2,%d,%d,%s", logged, cliID, len, name);
    totlen = strlen (msg);

    if ((nwrite = send_data_MQ (mqid, public, msg, totlen)) < 0)
    {
        return fatal("message write failed. Check server status\n");
    }

    if (rcv_data_MQbl (mqid, cliID, resp) < 0)
    {
        return fatal("message read failed\n");

    }
    move = getNumMQ(resp, &ans);
    move += readNumMQ(resp+ move, &pubcliID);
    logged = pubcliID;

    /*Se splitea dependiendo de los parámetros.*/
    if (splitVal == 't')
        splitRet = split(listenSrvMQ, NULL, (void *)&threads[LISTSRV_SPLIT],
                    splitVal, sighandLSMQ);
    else
        splitRet = split(listenSrvMQ, NULL, (void *)&sons[LISTSRV_SPLIT],
                    splitVal, sighandLSMQ);

    if ( splitRet != 1)
        return fatal ("Split failed\n");


    return 1;
}
int listaMQ(void)
{
    extern int logged;
    char msg[100] = {0};
    int nwrite, len, totlen;

    len = strlen (sess_name);

    sprintf(msg, "%d,%d,%d,%s", logged, COM_LIST, len, sess_name);
    totlen = strlen (msg);

    if ((nwrite = send_data_MQ (mqid, public, msg, totlen)) < 0)
        fatal("message write failed. Check server status\n");

    return 1;
}

void atenderListaMQ(char * msg)
{
    int servID, comm;
    int name_len;
    char dir[50] = {0};
    char aux_msg[MSGSIZE+1] = {0};
    int move = 0;
    char out_msg[MSGSIZE +1] = {0};
    int size, index = 1;

    move = readNumMQ(msg, &servID);

    sprintf(out_msg, "%d,%d", COM_ACK, cliID);
    size = strlen(out_msg);
    send_data_MQ (mqid, servID, out_msg, size);

    if (rcv_data_MQbl (mqid, cliID, aux_msg)< 0)
    {
        fatal ("msg read failed\n");
        return;
    }

    move = getNumMQ (aux_msg, &comm);

    while (comm != COM_END)
    {
        move += getNumMQ (aux_msg + move, &name_len);

        if ((move += readParamMQ (aux_msg + move, dir)) < 0)
        {
            fatal ("msg read failed\n");
            return ;
        }

        printf("%2d %s\n", index++, dir);

        while (name_len)
        {
            dir[--name_len] = 0;
        }

        sndMQAns(mqid, servID, COM_ACK);


        clrtext(aux_msg, MSGSIZE+1);
        if (rcv_data_MQbl (mqid, cliID, aux_msg)< 0)
        {
            fatal ("msg read failed\n");
            return ;
        }
        move = getNumMQ (aux_msg, &comm);
    }

    return;
}

int agregarMQ(void)
{
    char msg[100] = {0};
    char dir[50] = {0};
    int nwrite, len, totlen;

    fprintf (stdout, "\nInsert a Dir: ");
    getLine (dir, MAX_COMMAND_LEN, stdin);

    len = strlen(sess_name);
    len += strlen(dir);
    len += 1; /* Por la coma */

    sprintf(msg, "%d,%d,%d,%s,%s", logged, COM_ADD, len, sess_name, dir);
    totlen = strlen (msg);


    if ((nwrite = send_data_MQ (mqid, public, msg, totlen)) < 0)
        fatal("message write failed. Check server status\n");


    return 1;
}

void atenderAddMQ (char * msg)
{
    char currPath[FILE_LEN];
    char dir[MAX_DIR_LEN] = {0};
    int comm, nread, path_size, size;
    int servID, move = 0;
    char path[100] = {0};
    char buffer[BUF_SIZE] = {0};
    FILE * pfile;
    char aux_msg[MSGSIZE +1] = {0};
    char out_msg[MSGSIZE +1] = {0};
    char newpath[100] = {0};

    move = getNumMQ(msg, &servID);
    move += getNumMQ(msg + move, &size);
    move += readParamMQ (msg+move, dir);

    dir[size] = 0;
    sprintf(currPath,"%s/%s",syncPath, dir);

    if (!startFolder(currPath))
    {
        fatal ("Couldn't startFolder.\n");
        return ;
    }

    sprintf(out_msg, "%d,%d", COM_ACK, cliID);
    size = strlen(out_msg);
    send_data_MQ (mqid, servID, out_msg, size);

    if (rcv_data_MQbl (mqid, cliID, aux_msg)< 0)
    {
        fatal ("msg read failed\n");
        return ;
    }

    move = getNumMQ(aux_msg, &comm);

    while (comm != COM_END)
    {

        move += getNumMQ(aux_msg + move, &path_size);
        move +=getNumMQ(aux_msg + move, &size);
        sprintf(path, "%s", aux_msg+move);

        /*it's a dir*/
        if (size == -1)
        {
            mkdir(path, 0744);
            sndMQAns(mqid, servID, COM_ACK);
        }
        else
        {
            sprintf(newpath, "%s.new", path);
            if((pfile = fopen(newpath, "w")) == NULL)
            {
                fatal ("Error creating file\n");
                return ;
            }

            nread = 0;
            sndMQAns(mqid, servID, COM_ACK);
            while (size > 0)
            {
                if (size >= BUF_SIZE)
                    nread = BUF_SIZE;
                else
                    nread = size;

                if (nrcv_data_MQ (mqid, cliID, buffer, nread) < 0)
                    {
                        sndMQAns(mqid, servID, COM_ERR);
                        printf ("msg read failed\n");
                    }

                    if ((fwrite(buffer, 1, nread, pfile)) < nread)
                    {
                        sndMQAns(mqid, servID, COM_ERR);
                        printf ("File write failed\n");
                    }

                    sndMQAns(mqid, servID, COM_ACK);

                    size -= nread;

            }
            if ((fclose (pfile)) == EOF)
                printf ("file close failed\n");
            if (rename(newpath, path) != 0)
            {
                    printf ("Error renaming %s\n", newpath);
                    return;
            }
        }
        clrtext(aux_msg, MSGSIZE+1);
        if (rcv_data_MQbl (mqid, cliID, aux_msg) < 0)
        {
            fatal ("msg read failed\n");
            return ;
        }

        move = getNumMQ(aux_msg, &comm);
    }

    if(setWatchs(currPath, &w) == -1)
    {
        fprintf(stderr, "Error en setWatchs\n");
        return ;
    }

    printf("%s added successfully\n", dir);
    return;
}

int removerMQ (void)
{
    int len, nwrite, totlen;
    char msg [MSGSIZE] = {0};
    char dir[MAX_DIR_LEN] = {0};

    fprintf (stdout, "\nInsert a Sync Dir: ");
    getLine (dir, MAX_DIR_LEN, stdin);

    if (isDir(dir) != 1)
    {
        printf("%s is not a dir\n", dir);
        return 1;
    }

    len = strlen (sess_name);
    len += strlen (dir);
    len += 1;

    sprintf(msg, "%d,%d,%d,%s,%s", logged, COM_REMOVE, len, sess_name, dir);
    totlen = strlen (msg);

    if ((nwrite = send_data_MQ (mqid, public, msg, totlen)) < 0)
       return fatal("message write failed. Check server status\n");

    printf("Se intentara remover el dir: %s\n", dir);

    return 1;

}

void atenderRemoveMQ(char * msg)
{
    int size;
    char dir[MAX_DIR_LEN] = {0};
    char w_dir[MAX_DIR_LEN] = {0};
    int move, serv;

    move = getNumMQ(msg , &size);
    move += getNumMQ(msg+move, &serv);
    sprintf(dir, "%s", msg+move);

    sprintf(w_dir,"./%s", dir);
    if ((remWatch(&w, w_dir)) == -1)
        fatal ("Couldn't remove watch of dir\n");

    return ;

}
int salirMQ (void)
{
    int len, nwrite, totlen;
    char msg [MSGSIZE];

    len = strlen (sess_name);

    sprintf(msg, "%d,%d,%d,%s", logged, COM_CLOSE, len, sess_name);
    totlen = strlen (msg);

    if ((nwrite = send_data_MQ (mqid, public, msg, totlen)) < 0)
        return fatal("message write failed. Check server status\n");

    return 1;

}


void readCommandsMQ (void)
{
    int i;
    int cant_comms = 6;
    char command[MAX_COMMAND_LEN+1] = {0};
    extern int logged;

    char * commands[] = {"nombre", "lista", "agregar", "remover", "salir", "commit"};
    int (*pFunct[]) (void)= { nombreMQ, listaMQ, agregarMQ,
                                    removerMQ, salirMQ, commitMQ};

    fprintf (stdout, "\n<>: ");
    getLine (command, MAX_COMMAND_LEN, stdin);

    for (i=0 ; i < cant_comms+1 ; i++)
    {
        if (i == cant_comms)
        {
           fprintf (stdout, "\nError: Invalid command\n<>: ");
           getLine (command, MAX_COMMAND_LEN, stdin);
           i = -1;
        }
        else if (strcmp (command, commands[i]) == 0)
        {
            if(i == QUIT_POS)
            {
                if (logged)
                {
                    closeAllMQ();
                    waitSplits(threads, SPLITS_QUANTITY, splitVal);
                    logged = 0;
                }
                exit(0);
                return;
            }

            if (i == NAME_POS)
            {
                pFunct[i] ();
            }
            else
            {
                if (!logged)
                {
                    fprintf (stdout, "Not logged in.\n");
                }
                else
                {
                    pFunct[i] ();
                }
            }
            fprintf (stdout, "\n<>: ");
            getLine (command, MAX_COMMAND_LEN, stdin);
            i = -1;
        }
    }

    return;
}

int commit_fileMQ (char * path, int type)
{
    int len, totlen, nwrite;
    char msg[MSGSIZE] = {0};
    char aux_msg[MSGSIZE] = {0};
    char dir_path[FILE_LEN] = {0};
    int flag = 0, i;

    len = strlen (path);

    for (i = 0; i < len && flag < 2; i++)
    {
        dir_path[i] = path[i];

        if (path[i] == '/')
        {
            flag++;
        }
    }
    sprintf(aux_msg, "%s,%s,%d", sess_name, path, type);

    len = strlen(aux_msg);

    if (!canCommit (dir_path))
    {
        printf("Conflicts, can't commit\n");
        return 0;
    }

    sprintf(msg, "%d,%d,%d,%s", logged, COM_COMMIT, len, aux_msg);
    totlen = strlen (msg);

    if ((nwrite = send_data_MQ (mqid, public, msg, totlen)) < 0)
        return fatal("message write failed. Check server status\n");

    return 1;
}

void atenderCommitMQ (char * msg)
{
    int size, servID;
    char path[FILE_LEN] = {0};
    int back, move;
    char aux_msg[MSGSIZE+1] = {0};
    char out_msg[MSGSIZE+1] = {0};
    int out_size;


    move = getNumMQ(msg, &servID);
    move += getNumMQ(msg + move, &size);
    move += readParamMQ (msg+move, path);

    sprintf(out_msg, "%d,%d", SND_PRIV, cliID);
    out_size = strlen(out_msg);
    send_data_MQ (mqid, servID, out_msg, out_size);

    if (rcv_data_MQbl (mqid, cliID, aux_msg)< 0)
    {
        fatal ("msg read failed\n");
        return ;
    }

    move = getNumMQ(aux_msg, &back);

    if (back != COM_ACK)
    {
        fatal("Error received\n");
        return;
    }

    if (snd_file_MQ (mqid, servID, cliID , path, 0) < 0)
    {
        printf ("%s not commited\n", path);
        return ;
    }

    clrtext(aux_msg, MSGSIZE +1);

    if (rcv_data_MQbl (mqid, cliID, aux_msg)< 0)
    {
        fatal ("msg read failed\n");
        return ;
    }

    move = readNumMQ(aux_msg, &back);
    if (back != COM_ACK)
    {
        printf ("%s not commited, error received\n", path);
        return ;
    }
    return ;
}

int commitMQ (void)
{
    char aux_path[FILE_LEN] = {0};
    int resp;
    int type = 0;
    char chtype[MAX_COMMAND_LEN] = {0};
    char  * path;

    fprintf (stdout, "\nInsert a Path: ");
    getLine (aux_path, FILE_LEN, stdin);

    path = strdup(aux_path);

    fprintf (stdout, "\nAdd (1) or Delete(0): ");
    getLine (chtype, MAX_COMMAND_LEN, stdin);

    sscanf(chtype, "%d", &type);

    resp = commit_fileMQ (path, type);

    if (resp == 1)
        printf("%s commited OK\n", path);
    else
        printf("%s commited ERROR\n", path);

    return 1;
}

void * listenSrvMQ (void *parmsLS)
{
    fd_set master_set, working_set;
    char ch;
    struct timeval tw, tm;

    tm.tv_sec  = SEC_TIMEOUT;
    tm.tv_usec = 0;
    FD_ZERO(&master_set);

    /*Inicializo w*/
    w.waList = NULL;
    if ((w.fd = notify()) == -1)
    {
        fprintf(stderr, "Error al llamar a notify()\n");
        return (void *)NULL;
    }
    FD_SET(w.fd, &master_set);

    while (doLS)
    {

        memcpy(&working_set, &master_set, sizeof(master_set));
        memcpy(&tw, &tm, sizeof(struct timeval));
        if (listenQueueMQ() == -1)
        {
            printf("Error reading queue\n");
            return (void *)NULL;
        }

        if( select(w.fd + 1, &working_set, (fd_set *)0, (fd_set *)0, &tw) < 0)
        {
            if (errno == EINTR)
                continue;
            else
            {
                fatal ("select failed\n");
                return (void *)NULL;
            }
        }

        if (FD_ISSET (0, &working_set))
        {
            read(0, &ch, 1);
            printf("%c\n", ch);
        }

        if (FD_ISSET (w.fd, &working_set))
        {
            makeCommitMQ();
        }
    }

    return (void *)NULL;
}

int takeSrvMQ (char * msg)
{
    int ret = 0;
    int cant = 0;

    cant = getNumMQ (msg, &ret);

    switch (ret)
    {
        case COM_SND_DIRLIST:
            atenderListaMQ(msg + cant);
            break;

        case COM_SND_FILES:
            printf("Add in progress!\n");
            atenderAddMQ(msg + cant);
            break;

        case COM_RCV_COMMIT:
            printf("Commit in progress!\n");
            atenderCommitMQ(msg + cant);
            break;

        case WILL_UPDATE:
            printf("Will update!\n");
            atenderWillUpdateMQ(msg + cant);
            break;

        case COM_SND_COMMIT:
            printf("Update in progress!\n");
            atenderUpdateMQ(msg + cant);
            break;

        case COM_RMV_OK:
            printf("Remove ok!\n");
            atenderRemoveMQ(msg + cant);
            break;

        case COMMIT_OK:
            printf("Commit (del) ok!\n");
            break;

        case DIR_ERR:
            printf("Invalid dir!\n");
            break;

        case IS_SYNC:
            printf("Dir already syncronized\n");
            break;

        case IS_BUSY:
            printf("Performing another action, please try later\n");
            return -2;
            break;

        case COM_ERR:
            printf("Error occurred\n");
            break;

        default :
            printf("Command not understood\n");
        }

    return 1;
}

int makeCommitMQ(void)
{
    int resp;
    int i = 0, len;
    char buf[BUF_LEN_NOTIF] = {0};
    char * path = NULL;
    struct inotify_event *event;
    char completePath[FILE_LEN] = {0};
    int flag;

    len = read(w.fd, buf, BUF_LEN_NOTIF);
    if(len == -1)
    {
        fprintf(stderr, "Error en read\n");
        return 0;
    }
    i = 0;

    while (i < len)
    {
        flag = 0;
        event = (struct inotify_event *) &buf[i];
        if (event->len == 0)
        {
            i += EVENT_SIZE + event->len;
            continue;
        }
        if ((path = getWatchCompletePath(event, &w)) == NULL)
        {
            i += EVENT_SIZE + event->len;
            continue;
        }
        sprintf(completePath, "%s/%s", path, event->name);
        free(path);
        path = NULL;

        if( (strcmp(fileExt(event->name), ".new") != 0) &&
            (strcmp(fileExt(event->name), ".old") != 0) &&
            (strcmp(fileExt(event->name), ".mine") != 0) )
        {
            if(strcmp(completePath, lastComm) != 0)
            {
                switch(event->mask)
                {
                case MOVE_TO_MASK:
                case ADD_DIR:
                case ADD_MASK:
                    do{
                        resp = commit_fileMQ( completePath, 1);
                        if (resp)
                            while((flag = listenQueueMQ()) == 0);
                     }while(flag == -2);
                    break;

                case MOD_MASK:
                    do{
                        resp = commit_fileMQ( completePath, 1);
                        if (resp)
                            while((flag = listenQueueMQ()) == 0);
                    }while( flag == -2);
                    break;

                case DEL_DIR:
                    do{
                        resp = commit_fileMQ( completePath, 2);
                        if (resp)
                            while((flag = listenQueueMQ()) == 0);
                    }while(flag == -2);
                    i += EVENT_SIZE + event->len;
                    continue;
                    break;

                case MOVE_FROM_MASK:
                case DEL_MASK:
                    do{
                        resp = commit_fileMQ( completePath, 0);
                        if (resp)
                            while((flag = listenQueueMQ()) == 0);
                    }while(flag == -2);
                    break;


                default:
                    printf("Error en makeCommit con mask = %u\n", event->mask);
                    break;
                }
            }
            else
                clrtext(lastComm, FILE_LEN);
        }
        else
        {
            int k = strlen(completePath) - 1;
            sprintf(lastComm, "%s", completePath);
            while(lastComm[k] != '.' && k)
                k--;
            if (k)
                lastComm[k] = 0;
        }

        if(event->mask != DEL_DIR)
        {
            if(update(&w, event) == -1)
            {
                fprintf(stderr, "Error en upgrade\n");
            }
        }
        i += EVENT_SIZE + event->len;
    }

    return 1;
}

void atenderUpdateMQ (char * msg)
{
    char msgbuf[100] = {0};
    char currPath[FILE_LEN];
    char dir[50] = {0};
    char aux_dir[MAX_DIR_LEN] = {0};
    int comm, nread, path_size, size;
    char path[100] = {0};
    char buffer[BUF_SIZE] = {0};
    FILE * pfile;
    int type = 5;
    int servID, move;
    char out_msg[MSGSIZE+1] = {0};
    char aux_msg[MSGSIZE+1] = {0};
    char newpath[100] = {0};


    move = getNumMQ(msg, &servID);
    move += getNumMQ(msg + move, &size);
//    move += readParamMQ (msg+move, aux_dir);

    sprintf(aux_dir, "%s", msg + move);
    getDirType (aux_dir, dir, &type);

    sprintf(currPath,"%s/%s",syncPath, dir);


    sprintf(out_msg, "%d,%d", COM_ACK, cliID);
    size = strlen(out_msg);
    send_data_MQ (mqid, servID, out_msg, size);


    if (type == ADD_MOD)
    {
        if (rcv_data_MQbl (mqid, cliID, aux_msg)< 0)
        {
            fatal ("msg read failed\n");
            return ;
        }

        move = getNumMQ(aux_msg, &comm);
        move += getNumMQ(aux_msg + move, &path_size);

        sprintf(msgbuf, "%s", aux_msg + move);
        msgbuf[path_size] = 0;
        sscanf (msgbuf, "%d,%s", &size, path);
        sprintf(newpath, "%s.new", path);

        /*it's a dir*/
        if (size == -1)
        {
            if (mkdir(path, 0744) == -1)
            {
                printf("ERROR: creating dir: %s\n", path);
                return ;
            }
            sprintf(lastComm, "%s", path);

            sndMQAns(mqid, servID, COM_ACK);
        }
        else
        {
            if((pfile = fopen(newpath, "w")) == NULL)
            {
                fatal ("Error creating file\n");
                return ;
            }

            nread = 0;
            sndMQAns(mqid, servID, COM_ACK);
            while (size > 0)
            {
                if (size >= BUF_SIZE)
                    nread = BUF_SIZE;
                else
                    nread = size;

                if (nrcv_data_MQ (mqid, cliID, buffer, nread) < 0)
                {
                    sndMQAns(mqid, servID, COM_ERR);
                    printf ("msg read failed\n");
                    return ;
                }

                if ((fwrite(buffer, 1, nread, pfile)) < nread)
                {
                    sndMQAns(mqid, servID, COM_ERR);
                    printf ("File write failed\n");
                    return ;
                }

                sndMQAns(mqid, servID, COM_ACK);

                size -= nread;

            }

            if ((fclose (pfile)) == EOF)
            {
                printf ("file close failed\n");
                return ;
            }
            if (rename(newpath, path) != 0)
            {
                    printf ("Error renaming %s\n", newpath);
                    return;
            }
        }
    }
    else if(type == DEL_COMMIT)
    {
        sprintf(newpath, "%s.new", dir);

        if (remove(dir) != 0)
        {
                //sndFifoAns(fifo_serv, COM_ERR); TODO:
        }
        else
                //sndFifoAns(fifo_serv, COM_ACK); TODO:
            sprintf(lastComm, "%s", dir);
    }

    else if(type == DEL_DIR_COMMIT)
    {

        if (rmdir(dir) != 0)
        {
                //sndFifoAns(fifo_serv, COM_ERR);
        }
        else
                //sndFifoAns(fifo_serv, COM_ACK);
            sprintf(lastComm, "%s", dir);
    }

    return;
}

void
atenderWillUpdateMQ(char * msg)
{
    char  minePath[FILE_LEN] = {0};
    char dir[50] = {0};
    int move, size;

    move = getNumMQ(msg + move, &size);
    move += readParamMQ (msg+move, dir);

    sprintf(minePath, "%s.mine", dir);

    cp(dir, minePath);

    printf("Conflicts occured, fix before commiting\n");

    return ;
}

int listenQueueMQ()
{
    struct mymsg msg;
    int rtrn, i;
    char resp[FILE_LEN] = {0};

    msg.mtype = pubcliID;

    for(i = 0; i < 5; i++)
    {
        if ((rtrn = msgrcv(mqid, &msg, FILE_LEN, pubcliID, IPC_NOWAIT)) == -1)
        {
            if(errno != ENOMSG)
            {
                printf("msgop: msgrcv failed");
                return -1;
            }
        }
        else
        {
            sprintf(resp, "%s", msg.mtext);
            return takeSrvMQ(resp);
//            return 1;

        }
        usleep(100);
    }
    return 0;
}

int
rcv_data_MQbl (int mqid, int mqtype, char * r_msg)
{
    struct mymsg msg;
    int rtrn = 0;

    msg.mtype = mqtype;
    clrtext(msg.mtext, FILE_LEN);

    errno = ENOMSG;

    do
    {
        if ((rtrn = msgrcv(mqid, &msg, MSGSIZE, mqtype, IPC_NOWAIT)) == -1)
        {
            if(errno != ENOMSG)
            {
                printf("msgop: msgrcv failed");
                return -1;
            }
        }
        else
        {
            sprintf(r_msg, "%s", msg.mtext);

            return rtrn;
        }
    } while (doLS);

    return 1;
}

void sighandINTMQ(int signo)
{
    closeAllMQ();
}

void closeAllMQ (void)
{
    int i, stat;

    printf("\nClosing Splits\n");
    doLS = 0;

    if (logged)
    {
        salirMQ();
        if (splitVal == 't')
        {
            for( i = 0 ; i < SPLITS_QUANTITY ; i++)
            {
                pthread_join(threads[i], NULL);
            }
        }
        else
        {
            for( i = 0 ; i < SPLITS_QUANTITY ; i++)
            {
                kill(sons[i], SIGUSR1);
                waitpid (sons[i], &stat, 0);
            }
        }

    }

    exit(0);
    return;
}

void sighandLSMQ(int signo)
{
    printf("Closing Client...\n");
    doLS = 0;

    return;
}
